using System;
using System.ServiceModel;

using Pegasus.Log4Net;

namespace Pegasus.ServiceModel
{
	/// <summary>
	/// This class is used to receive messages from the peer network and pass
	/// them on to the peer network manager.
	/// </summary>
	[ServiceBehavior( InstanceContextMode = InstanceContextMode.Single )]
	internal class PrivateReceiver : IPrivate
	{
		// Local Instance Values
		private ILog m_log = LogManager.GetLogger( typeof( PrivateReceiver ) );
		private PeerNetworkManager m_peerNetManager;

		/// <summary>
		/// Initializes a new instance of the <see cref="PrivateReceiver"/> class.
		/// </summary>
		public PrivateReceiver( PeerNetworkManager peerNetManager )
		{
			m_log.DebugFormat( "PrivateReceiver( peerNetManager = {0} )", peerNetManager );
			m_peerNetManager = peerNetManager;
		}

		/// <summary>
		/// Pings the specified node.
		/// </summary>
		/// <param name="sender">The name of the node sending the message.</param>
		/// <returns>
		/// True if the node is online, otherwise false.
		/// </returns>
		public bool Ping( string sender )
		{
			m_log.DebugFormat( "Ping( sender = {0} )", sender );
			return m_peerNetManager.IsConnected;
		}

		/// <summary>
		/// Sends the message.
		/// </summary>
		/// <param name="sender">The sender.</param>
		/// <param name="message">The message.</param>
		/// <returns>The return value.</returns>
		public object SendPrivateMessage( string sender, object message )
		{
			m_log.DebugFormat( "SendPrivateMessage( sender = {0}, message = {1} )", sender, message );
			return m_peerNetManager.ReceivedPrivateMessage( sender, message );
		}

		/// <summary>
		/// Send a welcome to a new node in the mesh.  This message tells the new
		/// node who we are and gives our view of the mesh.
		/// </summary>
		/// <param name="sender">The name of the node sending the message.</param>
		/// <param name="nodeData">The node data.</param>
		public void SendWelcome( string sender, NodeData nodeData )
		{
			m_log.DebugFormat( "SendWelcome( sender = {0}, nodeData.Name = {1} )", sender, nodeData.Name );
			m_peerNetManager.ReceivedPrivateWelcome( sender, nodeData );
		}

		/// <summary>
		/// Sends an answer to a WhoIs request.
		/// </summary>
		/// <param name="sender">The name of the node sending the message.</param>
		/// <param name="nodeData">The node data.</param>
		public void SendWhoIsAnswer( string sender, NodeData nodeData )
		{
			m_log.DebugFormat( "SendWhoIsAnswer( sender = {0}, nodeData.Name = {1} )", sender, nodeData.Name );
			m_peerNetManager.ReceivedPrivateWhoIsAnswer( sender, nodeData );
		}
	}
}
